package com.seaside.park.api;

import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.seaside.common.bean.Result;
import com.seaside.parkCommon.bean.ParkPlace;
import com.seaside.parkCommon.mapper.ParkPlaceMapper;
import com.seaside.parkCommon.vo.ParkPlaceVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

@Slf4j
@Api(tags = "车位管理")
@RestController
@RequestMapping("/api/parkplace")
public class ParkPlaceAPI {

    @Autowired
    private ParkPlaceMapper parkPlaceMapper;

    @ApiOperation(value = "车位添加", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkPlace", dataTypeClass = ParkPlace.class, required = true, value = "车位信息")
    })
    @PostMapping("/add")
    public Result add(ParkPlace parkPlace, @ApiIgnore Authentication auth) {
        parkPlace.setUserName(auth.getName());
        if (parkPlaceMapper.insert(parkPlace) > 0) {
            return Result.OK("添加成功");
        } else {
            return Result.Error("添加错误");
        }
    }

    @ApiOperation(value = "查询车位分时临停时间段", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkPlace", dataTypeClass = ParkPlace.class, required = true, value = "车位信息")
    })
    @PostMapping("/queryTimeDuration")
    public Result queryTimeDuration(ParkPlace parkPlace, @ApiIgnore Authentication auth) {
        ParkPlace pp = parkPlaceMapper.selectOne(new QueryWrapper<ParkPlace>().eq("park_id", parkPlace.getParkId()).eq("user_name", auth.getName()));
        if (pp != null && pp.getParkId() > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            if (!Objects.isNull(pp.getStartTime()) && !Objects.isNull(pp.getEndTime())){
                String startTime = sdf.format(pp.getStartTime());
                String endTime = sdf.format(pp.getEndTime());
                Map<String, Object> timeDuration = new HashMap<>();
                timeDuration.put("startTime", startTime);
                timeDuration.put("endTime", endTime);
                return Result.OK("查询成功", timeDuration);
            }else{
                return Result.OK("未查询到当前车位预约时间段!", null);
            }
        }
        return Result.OK("未查询到当前车位信息!", null);
    }

    @ApiOperation(value = "车位修改", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkPlace", dataTypeClass = ParkPlace.class, required = true, value = "车位信息")
    })
    @PostMapping("/update")
    public Result update(ParkPlace parkPlace, @ApiIgnore Authentication auth) {
        parkPlace.setUserName(auth.getName());
        if (parkPlaceMapper.updateById(parkPlace) > 0) {
            return Result.OK("修改成功");
        } else {
            return Result.Error("修改失败");
        }
    }

    @ApiOperation(value = "车位临停时间段修改", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkPlace", dataTypeClass = ParkPlace.class, required = true, value = "车位信息")
    })
    @PostMapping("/updateTimeDuration")
    public Result updateTimeDuration(ParkPlace parkPlace, @ApiIgnore Authentication auth) {
        parkPlace.setUserName(auth.getName());
        ParkPlace pp = parkPlaceMapper.selectOne(new QueryWrapper<ParkPlace>().eq("park_id", parkPlace.getParkId()));
        pp.setStartTime(parkPlace.getStartTime());
        pp.setEndTime(parkPlace.getEndTime());
        if (parkPlaceMapper.updateById(pp) > 0) {
            return Result.OK("修改成功");
        } else {
            return Result.Error("修改失败");
        }
    }

    @ApiOperation(value = "根据当前用户的车位列表", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
    })
    @PostMapping("/userParkList")
    public Result<List<ParkPlaceVO>> getParkListByUserName(@ApiIgnore Authentication auth) {
        try{
            List<ParkPlaceVO> parkPlaceList = parkPlaceMapper.getParkPlaceByUserName(auth.getName());
            return Result.OK("查询成功!", parkPlaceList);
        } catch (Exception e) {
            log.error("查询失败：" + e.getMessage(), e);
            return Result.Error("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation(value = "车牌白名单添加", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "Header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkId", dataTypeClass = Integer.class, required = true, value = "车位ID"),
            @ApiImplicitParam(paramType = "query", name = "carIds", dataTypeClass = List.class, required = true, value = "车牌号白名单List<String>,List传入String"),
    })
    @PostMapping("/addCarId")
    public Result addCarId(int parkId, @RequestParam List<String> carIds, @ApiIgnore Authentication auth) {

        String userName = auth.getName();
        ParkPlace parkPlace = parkPlaceMapper.selectById(parkId);

        if (!userName.equals(parkPlace.getUserName())) {
            return Result.Error("该车位不是您拥有的车位!");
        }

        String ignor_list = parkPlace.getIgnorList();
        if(null == ignor_list) ignor_list="";
        for(int len=0;len<carIds.size();len++){
            if(len == 0 && ignor_list.equalsIgnoreCase("")) {
                ignor_list += carIds.get(len);
            }else {
                ignor_list += "|" + carIds.get(len);
            }
        }
        parkPlace.setIgnorList(ignor_list);
        if (parkPlaceMapper.updateById(parkPlace) > 0) {
            return Result.OK("添加白名单信息成功");
        } else {
            return Result.Error("添加白名单信息错误");
        }
    }

    @ApiOperation(value = "白名单查询", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "Header", name = "bearer", dataTypeClass = String.class, required = true, value = "用户token"),
            @ApiImplicitParam(paramType = "query", name = "parkId", dataTypeClass = Integer.class, required = true, value = "车位ID"),
    })
    @PostMapping("/queryIgnorList")
    public Result<List<String>> queryIgnorList(@RequestParam int parkId) {
        try {
            ParkPlace parkPlace = parkPlaceMapper.selectById(parkId);

            List<String> resultList = new ArrayList<>();
            List<String> ignorList = Arrays.asList(parkPlace.getIgnorList().split("\\|"));
            if (!CollectionUtils.isEmpty(ignorList)) {
                ignorList.forEach(ignor -> {
                    if (StringUtils.isNotBlank(ignor)) {
                        resultList.add(ignor);
                    }
                });
            }
            return Result.OK("查询成功!", resultList);
        } catch (Exception e) {
            log.error("查询失败：" + e.getMessage(), e);
            return Result.Error("查询失败：" + e.getMessage());
        }
    }
}
